package com.android.love.ui;

import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.android.love.R;
import com.android.love.adapter.MyAddressAdapter;
import com.android.love.net.UriHelper;
import com.android.love.util.ActivityUtil;
import com.android.love.util.LogUtil;
import com.android.love.vo.Address;
import com.android.love.vo.MyRequest;
import com.github.kevinsawicki.wishlist.ViewFinder;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class MyAddressActivity extends BasePageActivity {
	private List<Address> address_list = Collections.emptyList();
	private ViewFinder myAddressFinder;
	private ListView myAddressList;
	private PullToRefreshListView mPullToRefreshListView;
	private View footView;
	private int page = 1;
	/** 是否弹出加载中提示 **/
	private boolean show = true;
	private MyAddressAdapter myAddressAdapter;
	private int position;
	private boolean result;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ADDRESS_EDIT_MSG:
				position = msg.arg1;
				LogUtil.i(TAG, "address_list---" + address_list.size());
				if (address_list != null && address_list.size() > 0) {
					Address address = address_list.get(position);
					Intent intent = new Intent(context, AddressActivity.class);
					intent.putExtra("address", address);
					startActivityForResult(intent, ADDRESS_EDIT);
				}

				break;
			case ADDRESS_CHECK:
				position = msg.arg1;
				// if (address_list != null && address_list.size() > 0) {
				// Address address = address_list.get(position);
				// Intent intent = new Intent(context, AddressActivity.class);
				// intent.putExtra("address", address);
				// startActivityForResult(intent, ADDRESS_EDIT);
				// }

				if (address_list != null && address_list.size() > 0) {
					MyRequest req = new MyRequest();
					req.authority = UriHelper.REALM_NAME;
					req.path = UriHelper.URL_DEFAULT_ADDRESS;
					req.paramers = generateParams(page, true);
					getDataFromTask(context, ADDRESS_CHECK, req, result, true,
							false);

				}
				break;
			case ADDRESS_NOT_CHECK:
				ActivityUtil.show(MyAddressActivity.this, "必须设置一个默认地址");
				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		View myAddressView = inflater.inflate(R.layout.activity_my_address,
				null);
		setContentView(myAddressView);
		myAddressFinder = new ViewFinder(myAddressView);
		process();
		setListener();
		getData();
	}

	// @Override
	// protected void onResume() {
	// super.onResume();
	// LogUtil.i(TAG, "resume");
	// mHandler.addListener(this);
	// }
	// @Override
	// protected void onStart() {
	// super.onStart();
	// LogUtil.i(TAG, "onStart");
	// }

	@Override
	protected Boolean loadBottomTab() {
		// TODO Auto-generated method stub
		return false;
	}

	// @Override
	// protected void onDestroy() {
	// // TODO Auto-generated method stub
	// super.onDestroy();
	// LogUtil.i(TAG, "onDestroy");
	// mHandler.removeAllListener();
	// }

	@Override
	protected void process() {
		super.process();
		mPullToRefreshListView = myAddressFinder.find(R.id.lv_myaddress);
		myAddressList = mPullToRefreshListView.getRefreshableView();
		myAddressFinder.setDrawable(R.id.iv_shuaxin, R.drawable.btn_tianjia);
		myAddressFinder.setText(R.id.top_title, "地址管理");
		footView = LayoutInflater.from(context).inflate(R.layout.loading_item,
				null);
		TextView textView = (TextView) footView.findViewById(R.id.tv_loading);
		textView.setText("正在加载.....");
		myAddressList.addFooterView(footView);
		hide(footView);
	}

	@Override
	protected void getData() {
		super.getData();
		MyRequest req = new MyRequest();
		req.authority = UriHelper.REALM_NAME;
		req.path = UriHelper.URL_ADDRESS_LIST;
		req.paramers = generateParams(page, false);
		getDataFromTask(context, ADDRESS_LIST, req, address_list, show, true);
	}

	@Override
	protected void setListener() {
		super.setListener();
		myAddressFinder.find(R.id.iv_shuaxin).setOnClickListener(this);
		myAddressFinder.find(R.id.iv_top_meinv).setOnClickListener(this);
		mPullToRefreshListView.setMode(Mode.DISABLED);
		mPullToRefreshListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

					@Override
					public void onLastItemVisible() {
						LogUtil.i(TAG, "OnLastItemVisibleListener....");
						if (footView != null)
							footView.setVisibility(View.VISIBLE);
						show = false;
						page++;
						getData();
					}
				});
	}

	/**
	 * 得到传递的参数
	 * 
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public Map<String, String> generateParams(int page, boolean set_default) {
		JSONObject json = new JSONObject();
		TreeMap<String, String> params = new TreeMap<String, String>();
		params.put("app_key", "android");
		params.put("v", "1.0");
		if (set_default) {
			params.put("address_id", address_list.get(position).getAddress_id()
					+ "");
		} else {
			params.put("page", page + "");
			params.put("count", "10");
		}
		if (sp.getValue(USER_ID, 0) != 0)
			params.put("user_id", sp.getValue(USER_ID, 0) + "");
		if (!"".equals(sp.getValue(SIG, "")))
			params.put("sig", sp.getValue(SIG, ""));
		return params;
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.iv_shuaxin:
			Intent intent = new Intent(context, AddressActivity.class);
			intent.putExtra("new_address", true);
			startActivityForResult(intent, ADDRESS_ADD);
			break;
		case R.id.iv_top_meinv:
			finish(true);
			break;

		default:
			break;
		}

	}

	@Override
	public void handle(int tag, Object object) {
		super.handle(tag, object);
		hide(footView);
		switch (tag) {
		case ADDRESS_LIST:
			if (object != null) {
				address_list = (List<Address>) object;
				if (myAddressAdapter == null) {
					myAddressAdapter = new MyAddressAdapter(context,
							address_list, handler);
					myAddressList.setAdapter(myAddressAdapter);
				} else {
					myAddressAdapter.notifyDataSetChanged();
				}
			}else{
				page--;
			}
			mPullToRefreshListView.onRefreshComplete();
			break;
		case ADDRESS_CHECK:
			if (object != null) {
				result = (Boolean) object;
				if (result) {
					sp.setValue("default_address", address_list.get(position)
							.getAddress());
					sp.setValue("default_address_id", address_list
							.get(position).getAddress_id());
					sp.setValue("default_consignee", address_list.get(position)
							.getConsignee());
					sp.setValue("default_mail", address_list.get(position)
							.getMail());
					sp.setValue("default_phone", address_list.get(position)
							.getPhone());
					sp.setValue("default_postal", address_list.get(position)
							.getPostal());
					for (Iterator iterator = address_list.iterator(); iterator
							.hasNext();) {
						Address address = (Address) iterator.next();
						address.setDefault_address(0);
					}
					address_list.get(position).setDefault_address(1);
					myAddressAdapter.notifyDataSetChanged();
					ActivityUtil.show(MyAddressActivity.this, "设置成功");
				} else {
					ActivityUtil.show(MyAddressActivity.this, "设置失败");
				}
			}
			mPullToRefreshListView.onRefreshComplete();
			break;

		default:
			break;
		}
	}

	//
	// @Override
	// public void handleMessage(Message msg) {
	// super.handleMessage(msg);
	// switch (msg.what) {
	// case ADDRESS_EDIT_MSG:
	// position = msg.arg1;
	// LogUtil.i(TAG, "address_list---" + address_list.size());
	// if (address_list != null && address_list.size() > 0) {
	// Address address = address_list.get(position);
	// Intent intent = new Intent(context, AddressActivity.class);
	// intent.putExtra("address", address);
	// startActivityForResult(intent, ADDRESS_EDIT);
	// }
	// break;
	//
	// default:
	// break;
	// }
	// }

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);
		if (arg0 == ADDRESS_EDIT) {
			if (arg2 != null) {
				boolean delete = arg2.getBooleanExtra("delete", false);
				if (delete) {
					address_list.remove(position);
					myAddressAdapter.notifyDataSetChanged();
				} else {
					Address address = (Address) arg2
							.getSerializableExtra("address");
					if(address!=null){
						address_list.remove(position);
						address_list.add(position, address);
						myAddressAdapter.notifyDataSetChanged();
					}
				}
			}
		}
		if (arg0 == ADDRESS_ADD) {
			if (arg2 != null) {
				Address address = (Address) arg2
						.getSerializableExtra("address_add");
				if(address!=null){
					address_list.add(address);
					myAddressAdapter.notifyDataSetChanged();
				}
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& keyCode == KeyEvent.KEYCODE_BACK) {
			finish(true);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
